import { Router, RouteRecordRaw } from "vue-router";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { useAsyncRouteStore } from "@/store/modules/asyncRoute";
import { storage } from "@/utils/lib/Storage";
import { useUserStore } from "@/store/modules/user";
import { constantRouter, asyncRoutes } from './index'

const whiteRouter = ["/login", "/"];
export function createRouterGuards(router: Router) {
	router.beforeEach(async (to, from, next) => {
		const token = storage.get(ACCESS_TOKEN, '');
		const asyncRouteStore = useAsyncRouteStore()
		const userStore = useUserStore()
		if (whiteRouter.includes(to.path)) {
			next()
			return
		}
		if (!token) {
			next("/login");
			return
		}
		if (asyncRouteStore.isAddRoute) {
			next()
			return
		}

		// 获取权限
		const permission = await asyncRouteStore.generateRoutes(userStore.info.user_id)
		// 路由查找
		const routes = asyncRoutes.filter(item => permission.includes(item?.meta?.title))
		// 添加路由
		asyncRouteStore.setAsyncRoutes(routes)
		console.log('routes',routes);
		
		routes.forEach(item => {
			router.addRoute(item as RouteRecordRaw)
		})
		
		asyncRouteStore.setIsAddRoute(true)
		// 解决router4版本的第一次路由不匹配问题
		next({...to,replace:true});
	});

	router.afterEach((to, from, next) => {
		// 设置标题
		document.title = (to?.meta?.title as string) || document.title;

		// 设置需要被缓存的组件名
		const asyncRouteStore = useAsyncRouteStore();
		const keepAliveComponents: string[] = asyncRouteStore.keepAliveComponents;
		const currentComponentName: any = to.matched.find(
			(item) => item.name == to.name
		)?.name;
		if (
			currentComponentName &&
			!keepAliveComponents.includes(currentComponentName) &&
			to.meta.isKeepAlive
		) {
			asyncRouteStore.setKeepAliveComponents(currentComponentName);
		}
		console.log(keepAliveComponents);

		const Loading = window["$loading"] || null;
		Loading && Loading.finish();
	});
}
